package com.ruoyi.feike.controller;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.ruoyi.activiti.domain.dto.ActTaskDTO;
import com.ruoyi.activiti.domain.vo.SearchVo;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.*;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.feike.domain.AnnualReviewy;
import com.ruoyi.feike.domain.BasicInformation;
import com.ruoyi.feike.domain.WholesalePerformanceCurrently;
import com.ruoyi.feike.domain.vo.AnnualReviewyHistoryVO;
import com.ruoyi.feike.domain.vo.AnnualReviewyVO;
import com.ruoyi.feike.service.IAnnualReviewyService;
import com.ruoyi.framework.config.ServerConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * feikeController
 *
 * @author ruoyi
 * @date 2022-07-07
 */
@RestController
@RequestMapping("/feike/annual_review")
public class AnnualReviewyController extends BaseController {
    @Autowired
    private IAnnualReviewyService annualReviewyService;

    @Autowired
    private ServerConfig serverConfig;

    /**
     * 查询feike带任务列表列表
     */
    // @PreAuthorize("@ss.hasPermi('feike:feike:list')")
    @GetMapping("/annual_review")
    public TableDataInfo list(AnnualReviewy annualReviewy) {
        startPage();
        List<AnnualReviewy> list = annualReviewyService.selectAnnualReviewyAndTaskNameList(annualReviewy);
        return getDataTable(list);
    }

    /**
     * 查询feike列表
     */
    // @PreAuthorize("@ss.hasPermi('feike:feike:list')")
    @GetMapping("/lists")
    public TableDataInfo listById(AnnualReviewy annualReviewy) {
        startPage();
        List<AnnualReviewyVO> list = annualReviewyService.selectAnnualReviewyVOList(annualReviewy);
        return getDataTable(list);
    }

    /**
     * 查询feike列表
     */
    // @PreAuthorize("@ss.hasPermi('feike:feike:list')")
    @GetMapping("/listAll")
    public TableDataInfo listAll(AnnualReviewy annualReviewy, BasicInformation basicInformation) {
        startPage();
        List<AnnualReviewyHistoryVO> list = annualReviewyService.selectAnnualReviewyList(annualReviewy,basicInformation);
        return getDataTable(list);
    }

    //TODO
    /**
     * 导出feike列表
     */
    @PreAuthorize("@ss.hasPermi('feike:feike:export')")
    @Log(title = "feike", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(AnnualReviewy annualReviewy, BasicInformation basicInformation) {
        List<AnnualReviewyHistoryVO> list = annualReviewyService.selectAnnualReviewyList(annualReviewy,basicInformation);
        ExcelUtil<AnnualReviewyHistoryVO> util = new ExcelUtil<AnnualReviewyHistoryVO>(AnnualReviewyHistoryVO.class);
        return util.exportExcel(list, "feike");
    }

    /**
     * 获取feike详细信息
     */
    // @PreAuthorize("@ss.hasPermi('feike:feike:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return AjaxResult.success(annualReviewyService.selectAnnualReviewyById(id));
    }

    /**
     * 获取feike详细信息
     */
    // @PreAuthorize("@ss.hasPermi('feike:feike:query')")
    @GetMapping(value = "/ByInstanceId/{instanceId}")
    public AjaxResult getInfoByInstanceId(@PathVariable("instanceId") String instanceId) {
        return AjaxResult.success(annualReviewyService.selectAnnualReviewyByInstanceId(instanceId));
    }

    /**
     * 新增feike
     */
    // @PreAuthorize("@ss.hasPermi('feike:feike:add')")
    @Log(title = "feike", businessType = BusinessType.INSERT)
    @PostMapping
    //public AjaxResult add(@RequestBody AnnualReviewy annualReviewy)
    public AjaxResult add(@RequestBody Map<String, Object> map) {
        return toAjax(annualReviewyService.insertAnnualReviewy(map));
    }

    /**
     * 修改feike
     */
    // @PreAuthorize("@ss.hasPermi('feike:feike:edit')")
    @Log(title = "feike", businessType = BusinessType.UPDATE)
    @PutMapping
    //public AjaxResult edit(@RequestBody AnnualReviewy annualReviewy) {
    public AjaxResult edit(@RequestBody Map<String, Object> map) {
        System.out.println("修改=="+map);
        return toAjax(annualReviewyService.updateAnnualReviewy(map));
    }

    /**
     * 修改feike
     */
    // @PreAuthorize("@ss.hasPermi('feike:feike:edit')")
    @Log(title = "feike", businessType = BusinessType.UPDATE)
    @PutMapping("/closeUpdateAnnualReviewyObj/{instanceId}")
    //public AjaxResult edit(@RequestBody AnnualReviewy annualReviewy) {
    public AjaxResult closeUpdateAnnualReviewyObj(@PathVariable String instanceId) {
        String username = SecurityUtils.getLoginUser().getUsername();
        return toAjax(annualReviewyService.closeUpdateAnnualReviewyObj(instanceId,username));
    }

    @Log(title = "feike", businessType = BusinessType.UPDATE)
    @PutMapping("/openUpdateAnnualReviewyObj")
    //public AjaxResult edit(@RequestBody AnnualReviewy annualReviewy) {
    public AjaxResult openUpdateAnnualReviewyObj() {
        String username = SecurityUtils.getLoginUser().getUsername();
        annualReviewyService.openUpdateAnnualReviewyObj(username);
        return toAjax(1);
    }

    /**
     * 删除feike
     */
    // @PreAuthorize("@ss.hasPermi('feike:feike:remove')")
    @Log(title = "feike", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(annualReviewyService.deleteAnnualReviewyByIds(ids));
    }

    //TODO--待完善
    @RequestMapping("/uploads")
    public String uploadFile(MultipartFile[] files, HttpServletRequest request) {
        //String realPath = request.getServletContext().getRealPath("/img");
        String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();

        //创建年月日文件夹
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String res = simpleDateFormat.format(new Date());
        String year = res.substring(0, 4);   //2022
        String month = res.substring(4, 6);  //07
        String day = res.substring(6);      //08
        String fileUploadPath = path + "static/FileUpload/";
        //String fileUploadPath = path + "static/FileUpload/"+File.separator+year+File.separator+month+File.separator+day+File.separator;
        File fileUploadfolder = new File(fileUploadPath);
        //判断目录是否存在，不存在则创建目录
        if (!fileUploadfolder.exists()) {
            fileUploadfolder.mkdirs();
        }
        for (MultipartFile file : files) {
            //获取上传文件的源文件名称
            String oldName = file.getOriginalFilename();
            String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
            try {
                file.transferTo(new File(fileUploadfolder, newName));
                //打印上传文件的url
                System.out.println(request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/FileUpload/" + newName);
            } catch (IOException e) {
                e.printStackTrace();
                return "上传文件失败";
            }
        }
        return "上传文件成功";
    }

    /**
     * 根据id查询，给邮箱模板返回需要的信息
     */
    // @PreAuthorize("@ss.hasPermi('feike:feike:query')")
    @PostMapping(value = "/mailInfo/{instanceId}")
    public AjaxResult getMailInfo(@PathVariable("instanceId") String instanceId) {
        return AjaxResult.success(annualReviewyService.selectMailInfoByInstanceId(instanceId));
    }

    /**
     * 新增feike
     */
    // @PreAuthorize("@ss.hasPermi('feike:feike:add')")
    @Log(title = "feike", businessType = BusinessType.INSERT)
    @PostMapping("/startDM")
    //public AjaxResult add(@RequestBody AnnualReviewy annualReviewy)
    public AjaxResult startDM(@RequestBody Map<String, Object> map) {
        return toAjax(annualReviewyService.startDM(map));
    }

    /**
     * 新增feike
     */
    // @PreAuthorize("@ss.hasPermi('feike:feike:add')")
    @Log(title = "feike", businessType = BusinessType.INSERT)
    @PostMapping("/dmSelect")
    //public AjaxResult add(@RequestBody AnnualReviewy annualReviewy)
    public AjaxResult dmSelect(@RequestBody Map<String, Object> map) {
        return toAjax(annualReviewyService.dmSelect(map));
    }

    /**
     * 新增feike
     */
    // @PreAuthorize("@ss.hasPermi('feike:feike:add')")
    @Log(title = "feike", businessType = BusinessType.INSERT)
    @PostMapping("/startPLM")
    //public AjaxResult add(@RequestBody AnnualReviewy annualReviewy)
    public AjaxResult startPLM(@RequestBody Map<String, Object> map) {
        return toAjax(annualReviewyService.startPLM(map));
        //@PreAuthorize("@ss.hasPermi('feike:feike:query')")
    }

    @Log(title = "feike", businessType = BusinessType.INSERT)
    @PostMapping("/updateMain")
    public AjaxResult updateMain(@RequestBody Map<String, Object> map) {
        return toAjax(annualReviewyService.updateMain(map));
    }

    @GetMapping("/getMain/{taskId}")
    public AjaxResult getMain(@PathVariable("taskId") String taskId) {
        return AjaxResult.success(annualReviewyService.getMain(taskId));
    }

    //条件查询--搜索按钮方法
    @GetMapping(value = "/search")
    public TableDataInfo getPageInfo( SearchVo searchVo) {
        PageDomain pageDomain = TableSupport.buildPageRequest();

        Page<ActTaskDTO> hashMaps = annualReviewyService.selectProcessDefinitionSearchList(searchVo,pageDomain);
        return getDataTable(hashMaps);

    }

    @GetMapping("/indexData")
    public ResultData indexData(){
        CustomPage hashMaps = annualReviewyService.indexData();
        return getResult(hashMaps);
    }

    /**
     * 调用第三方接口进行数据查询刷新
     * @return
     */
    @PostMapping("/threeRefresh")
    public AjaxResult getRefreshList(@RequestBody Map<String, Object> map){
        // TODO 后面甲方提供了接口，在进行调用测试，获取数据进行刷新
        String urlStr="http://10.226.182.86:8081/CreditLoanSuspenseAPIUAT7/CreditInfo";   //第三方接口路径
        // 添加请求头信息
        JSONObject jsonObject = new JSONObject();
        Map<String, String > heads = new HashMap<>();
        // 使用json发送请求，下面的是必须的
        heads.put("Content-Type", "application/json;charset=UTF-8");

        /**
         * post请求
         ** headerMap是添加的请求头，
         body是传入的参数，这里选择json，后端使用@RequestBody接收
         */
        List dealerCodeList = new ArrayList();
        // String groupName = (String) map.get("groupName");
        List dealerNameList = (List) map.get("dealerName");
        System.out.println("dealerNameList=="+dealerNameList);
        // 根据集团名称和经销商名称获取dealercode对象   "DealerCode":[["L061701","M01002"],["L061702","M01003"]]
        List<Map<String,Object>> codeList =new ArrayList();
        if(dealerNameList!=null && dealerNameList.size()>0){
            for (int i = 0; i < dealerNameList.size(); i++) {

                String str = (String) dealerNameList.get(i);
                List dealerInformationList = annualReviewyService.getInfoListByDealerName(str);
                System.out.println("dealerInformationList=="+dealerInformationList);
                if (dealerInformationList!=null && dealerInformationList.size()>0){
                    for (int j = 0; j < dealerInformationList.size(); j++) {
                        Map<String,Object> dealerAndDealerCodeMap = new HashMap<>();
                        String dealerCodeStr = (String) dealerInformationList.get(j);
                        dealerAndDealerCodeMap.put(dealerCodeStr,str);
                        codeList.add(dealerAndDealerCodeMap);
                    }
                }
                dealerCodeList.add(dealerInformationList);
            }
        }
        System.out.println("codeList=="+codeList);
        System.out.println("dealerCodeList=="+dealerCodeList);
        // String jsonString = JSON.toJSONString(dealerCodeList);
        jsonObject.put("DealerCode",dealerCodeList);

        String response = HttpRequest.post(urlStr)
                                 .header("Content-Type", "application/json;charset=UTF-8")
                                 .body(jsonObject.toString())
                                 .execute()
                                 .body();
        System.out.println("response=="+response);

        Map<String,Object> mapObj=new HashMap<>();
        List<WholesalePerformanceCurrently> wholesalePerformanceCurrentlyList=new ArrayList<>();
        List<Map<String,Object>> crixpGradeLists = new ArrayList<>();

        cn.hutool.json.JSONObject entries = JSONUtil.parseObj(response);
        Integer code1 = (Integer) entries.get("Code");
        if (code1==200){
            // String dataList = entries.get("Data").toString();
            List data = (List) entries.get("Data");
            String strObj = JSON.toJSONString(data);
            data = JSON.parseArray(strObj);
            System.out.println("data===="+data);
            if (data!=null && data.size()>0){
                for (int i = 0; i < data.size(); i++) {
                    List firstList = (List) data.get(i);    //data中的第一个数组
                    System.out.println("firstList===="+firstList);
                    if (firstList!=null && firstList.size()>0){
                        for (int i1 = 0; i1 < firstList.size(); i1++) {
                            /*List dealerNameLists = (List) map.get("dealerName");
                            if(dealerNameLists!=null && dealerNameLists.size()>0){

                            }
                            for (int x = 0; x < dealerNameList.size(); x++) {
                                List<String> list = (List<String>) dealerCodeList.get(i1);

                                if(list.get(0).equals(dealerCode)){
                                    String str = (String) dealerNameList.get(x);

                                }

                            }*/
                            Map<String,Object> firstMap = (Map<String, Object>) firstList.get(i1); //data中的第一个数组中的第一个对象
                            String dealerCode = (String) firstMap.get("DealerCode");
                            List creditInfoList = (List) firstMap.get("CreditInfo");     //CreditInfo数组
                            System.out.println("dealerCode=="+dealerCode);
                            System.out.println("creditInfoList=="+creditInfoList);
                            Map<String,Object> tempObj = new HashMap<>();
                            if (creditInfoList!=null && creditInfoList.size()>0){

                                for (int i11 = 0; i11 < creditInfoList.size(); i11++) {
                                    Map<String,Object> creditInfoListFirstMap = (Map<String, Object>) creditInfoList.get(i11);//CreditInfo数组中的第一个对象
                                    String sector = (String) creditInfoListFirstMap.get("Sector");
                                    List crixpGradeList = (List) creditInfoListFirstMap.get("CrixpGrade");  //CreditInfo数组中的第一个对象中的CrixpGrade数组
                                    System.out.println("sector=="+sector);
                                    System.out.println("crixpGradeList=="+crixpGradeList);
                                    // int currentYear = new Date().getYear();
                                    Calendar calendar = Calendar.getInstance();
                                    int currentYear = calendar.get(Calendar.YEAR);
                                    System.out.println("currentYear==22=="+currentYear);
                                    int year =0;
                                    String grade ="";
                                    int year1 =0;
                                    String grade1 ="";
                                    for (int i2 = 0; i2 < crixpGradeList.size(); i2++) {
                                        Map<String,Object> creditInfoListFirstObj = (Map<String,Object>)crixpGradeList.get(i2);
                                        Object year2 = creditInfoListFirstObj.get("Year");
                                        System.out.println("year2===="+year2);
                                        System.out.println("currentYear=="+currentYear);
                                        if(String.valueOf(creditInfoListFirstObj.get("Year")).equals(String.valueOf(""+currentYear))){
                                            year =  currentYear;
                                            grade = (String) creditInfoListFirstObj.get("Grade");
                                        }
                                        if(String.valueOf(creditInfoListFirstObj.get("Year")).equals(String.valueOf(""+(currentYear-1)))){
                                            year1 = currentYear-1;
                                            grade1 = (String) creditInfoListFirstObj.get("Grade");
                                        }
                                    }

                                    for (Map<String, Object> stringObjectMap : codeList) {
                                        boolean contains=stringObjectMap.containsKey(dealerCode);  //判断是否包含指定的键值
                                        if(contains){  //如果条件为真
                                            tempObj.put("Dealer",stringObjectMap.get(dealerCode));
                                            tempObj.put("DealerCode",dealerCode);
                                            tempObj.put("lastYear",year1);
                                            tempObj.put("thisYear",currentYear);
                                            tempObj.put("thisYearGrade",grade);
                                            tempObj.put("lastYearGrade",grade1);
                                            crixpGradeLists.add(tempObj);
                                        }
                                    }

                                    List creditDetList = (List) creditInfoListFirstMap.get("CreditDet");  //CreditInfo数组中的第一个对象中的CreditDet数组
                                    if(creditDetList!=null && creditDetList.size()>0){
                                        for (int i112 = 0; i112 <creditDetList.size() ; i112++) {
                                            WholesalePerformanceCurrently wholesalePerformanceCurrently = new WholesalePerformanceCurrently();
                                            Map<String,Object> creditDetListFirstObj = (Map<String, Object>) creditDetList.get(i112);
                                            String limitType = (String) creditDetListFirstObj.get("LimitType");
                                            Integer creditLimit = (Integer) creditDetListFirstObj.get("CreditLimit");     // 我们这边是Double类型，传的是Integer类型
                                            Object expiryDate = creditDetListFirstObj.get("ExpiryDate");
                                            Object securityRatio = creditDetListFirstObj.get("SecurityRatio");
                                            Integer activeLimit = (Integer) creditDetListFirstObj.get("ActiveLimit");   // 我们这边是Double类型，传的是Integer类型
                                            Object activeOS =  creditDetListFirstObj.get("ActiveOS");       // 我们这边是Double类型，传的是Integer类型

                                            System.out.println("limitType=="+limitType);
                                            System.out.println("creditLimit=="+creditLimit);
                                            System.out.println("expiryDate=="+expiryDate.toString());
                                            System.out.println("securityRatio=="+securityRatio.toString());
                                            System.out.println("activeLimit=="+activeLimit);
                                            System.out.println("activeOS=="+activeOS);

                                            wholesalePerformanceCurrently.setDealername(dealerCode);
                                            wholesalePerformanceCurrently.setSector(sector);
                                            wholesalePerformanceCurrently.setLimitType(limitType);
                                            wholesalePerformanceCurrently.setCreditLimit(creditLimit.longValue());
                                            wholesalePerformanceCurrently.setActivatedLimit(activeLimit.longValue());
                                            wholesalePerformanceCurrently.setExpiredDates(expiryDate.toString());
                                            // wholesalePerformanceCurrently.setOs(Long.valueOf(String.valueOf(activeOS)));
                                            // wholesalePerformanceCurrently.setOs(activeOS);
                                            wholesalePerformanceCurrently.setActiveOS(""+activeOS);
                                            wholesalePerformanceCurrentlyList.add(wholesalePerformanceCurrently);
                                        }
                                    }
                                }

                            }


                        }

                    }

                }

            }

            Map<String,Object> dataSummaryMap = (Map<String, Object>) entries.get("DataSummary");
            if (dataSummaryMap!=null){
                Object dataCount =  dataSummaryMap.get("DataCount");  // BigDecimal
                Object creditInfoCount =  dataSummaryMap.get("CreditInfoCount");
                Object creditDetCount =  dataSummaryMap.get("CreditDetCount");
                Object creditLimitSum =  dataSummaryMap.get("CreditLimitSum");
                Object activeLimitSum =  dataSummaryMap.get("ActiveLimitSum");
                Object activeOSSum =  dataSummaryMap.get("ActiveOSSum");

                System.out.println("dataCount=="+dataCount);
                System.out.println("creditInfoCount=="+creditInfoCount);
                System.out.println("creditDetCount=="+creditDetCount);
                System.out.println("creditLimitSum=="+creditLimitSum);
                System.out.println("activeLimitSum=="+activeLimitSum);
                System.out.println("activeOSSum=="+activeOSSum);
            }
        }
        mapObj.put("wholesalePerformanceCurrently",wholesalePerformanceCurrentlyList);
        mapObj.put("crixpGrade",crixpGradeLists);
        System.out.println("crixpGradeLists===="+crixpGradeLists);

        return AjaxResult.success(mapObj);
    }

    /**
     * 通用上传请求
     */
    @PostMapping("/common/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            String originalFilename = file.getOriginalFilename();       // 文件的中文名
            System.out.println("fileName=="+fileName);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("url", url);
            ajax.put("originalFilename", originalFilename);
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 多文件上传请求
     */
    @PostMapping("/common/uploads")
    public AjaxResult uploadFiles(MultipartFile[] files) throws Exception
    {
        try
        {
            // AjaxResult ajax = AjaxResult.error("上传失败");
            List dataList=new ArrayList();
            for (MultipartFile file : files) {
                Map<String,String> map=new HashMap<>();
                // 上传文件路径
                String filePath = RuoYiConfig.getUploadPath();
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);   // 文件完整路径
                String url = serverConfig.getUrl() + fileName;              // 浏览器可以访问的url路径
                String originalFilename = file.getOriginalFilename();       // 文件的中文名
                System.out.println("fileName=="+fileName);
                map.put("fileName", fileName);
                map.put("url", url);
                map.put("originalFilename", originalFilename);
                dataList.add(map);
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("data", dataList);
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

}
